package cn.seaboot.admin.video;

import org.jetbrains.annotations.NotNull;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 截断输入流
 *
 * IO 复制过程中，只复制其中一部分
 * <p>
 * 前端开发过程中，使用 video 标签时，需要视频支持分段写出，
 */
public class PartialInputStream extends FilterInputStream {
    /**
     * 读取输入流前 n 个字节
     */
    private long remainingBytes;

    /**
     * @param in     输入流
     * @param length 需要截取的输入流
     */
    public PartialInputStream(InputStream in, long length) {
        super(in);
        this.remainingBytes = length;
    }

    @Override
    public int read(byte @NotNull [] b, int off, int len) throws IOException {
        if (remainingBytes <= 0) {
            return -1;
        }
        int bytesToRead = (int) Math.min(len, remainingBytes);
        int bytesRead = super.read(b, off, bytesToRead);
        if (bytesRead > 0) {
            remainingBytes -= bytesRead;
        }
        return bytesRead;
    }

    @Override
    public int read() throws IOException {
        if (remainingBytes <= 0) {
            return -1;
        }
        remainingBytes--;
        return super.read();
    }
}
